import {View, RichText} from "@tarojs/components";
import React, {useEffect, useRef, useState} from "react";
import Utils from "@/utils/common";
import {WebParams} from "@/common/apis/model";
import {useShareAppMessage, useShareTimeline} from "@tarojs/taro";
import RouthPath from "@/common/RouthPath";
import JsonUtils from "@/utils/json_utils";

definePageConfig({
  navigationBarTitleText: '',
  enableShareAppMessage: true,
  enableShareTimeline: true,
})

export default function Web_detail() {
  const [content, setContent] = useState<string>()
  const params = useRef<WebParams>()
  useEffect(() => {
    const p = Utils.getParamsByRouter(Utils.getI())
    if (p && p.data) {
       params.current = Utils.getObjectWithUrl<WebParams>(p.data)
      Utils.setTitle(params.current?.title)
      setContent(params.current?.content)
    }
  }, []);

   useShareAppMessage((res) => {
     return {
       title: params.current?.title, // 分享卡片的title
       path: Utils.getUrlWithObject(RouthPath.webDetail, {
         title: params.current?.title,
         content: params.current?.content
       }), // 分享卡片的小程序路径
       imageUrl: ''
     };
   })
  useShareTimeline(() => {
    // 确保数据已加载
    if (!params.current || !params.current?.content) {
      return {
        title: ``,
      };
    }
    const paramsForTimeline: Partial<WebParams> = {}; // Partial 允许部分属性
    if (params.current?.title) {
      paramsForTimeline.title = params.current?.title; // 传递整个 machineId 对象
    }
    if (params.current?.content) {
      paramsForTimeline.content = params.current?.content; // 传递整个 projectId 对象
    }
    const timelineDataString = JsonUtils.stringify(paramsForTimeline);
    const encodedTimelineData = encodeURIComponent(timelineDataString);
    return {
      title: params.current?.title,
      query: `data=${encodedTimelineData}`, // <--- 关键修改
    };
  })


  return (
    <View style={{
      width: '100%',
      height: '100vh',
      margin: '10px',
      padding: '10px',
      boxSizing: 'border-box',
    }}
    >
      <RichText
        nodes={content}
      />
    </View>
  )
}


